module database.mydb;

import ddbc.drivers.sqliteddbc;
import hibernated.core;
import models.user;
import models.role;
import models.menu;
import models.dept;
import utils.constant : Constant;

private SessionFactory factory;
public Session dbsess;

static this()
{
    EntityMetaData schema = new SchemaInfoImpl!(User, Role, Menu, Dept);
    SQLITEDriver driver = new SQLITEDriver();
    string[string] params;
    Dialect dialect = new SQLiteDialect();
    DataSource ds = new ConnectionPoolDataSourceImpl(driver, Constant.DB_URL, params);
    factory = new SessionFactoryImpl(schema, dialect, ds);
    dbsess = factory.openSession();
}

static ~this()
{
    dbsess.close();
    factory.close();
}

// void intDb()
// {
//     import std.file;

//     if (std.file.exists(Constant.DB_URL))
//     {
//         return;
//     }

//     EntityMetaData schema = new SchemaInfoImpl!(User, Role, Menu, Dept);

//     SQLITEDriver driver = new SQLITEDriver();
//     string[string] params;
//     Dialect dialect = new SQLiteDialect();

//     DataSource ds = new ConnectionPoolDataSourceImpl(driver, Constant.DB_URL, params);

//     // get connection
//     Connection conn = ds.getConnection();
//     scope (exit)
//     {
//         conn.close();
//     }

//     // create session factory
//     SessionFactory factory1 = new SessionFactoryImpl(schema, dialect, ds);
//     scope (exit)
//     {
//         factory1.close();
//     }
//     // create tables if not exist
//     factory1.getDBMetaData().updateDBSchema(conn, false, true);
// }
